import { invoke } from "@tauri-apps/api";
import { appWindow } from "@tauri-apps/api/window";
import { onRecv } from "./recv";

const EMIT_RECV_BYTES = "emit-recv-bytes";

async function init() {
    await appWindow.listen<number[]>(EMIT_RECV_BYTES, (item) => {
        onRecv(item.payload);
    });
}

init();

export const serialPort = {


    async getCurrentPortNames() {
        return await invoke('get_current_serial_ports') as string[];
    },

    async isOpen() {
        return await invoke('serial_port_is_open') as boolean;
    },

    async open(name: string, baudRate: number) {
        await invoke('serial_port_open', {
            name, baudRate
        });
    },

    async close() {
        await invoke('serial_port_close');
    },

    async write(buf: number[]) {
        await invoke('serial_port_write', {
            buf
        })
    },
}
